import MySQLdb
import sys
import os
import codecs
sys.stdout = codecs.getwriter('utf-8')(sys.stdout.detach())
import numpy as np
import pkuseg
import re
#import module
import torch
#import csv
#import openpyxl
import operator
from functools import reduce
import sys
from torch import nn
from torch.autograd import Variable
from torch import optim

curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)
db = MySQLdb.connect("localhost", "root", "ll00402", "ad", charset='utf8' )
cur=db.cursor()

class CNN(nn.Module):
    def __init__(self):  # (11,11) 11*11 
        super(CNN, self).__init__()

        self.layer1 = nn.Sequential(
            nn.Conv2d(1, 16, (3, 3)),  # 16,9,9
            nn.BatchNorm2d(16),
            nn.ReLU(inplace=True)
        )

        self.layer2 = nn.Sequential(
            nn.Conv2d(16, 32, (3, 3)),  # 32,7,7
            nn.BatchNorm2d(32),
            nn.ReLU(inplace=True),
        )

        self.layer3 = nn.Sequential(
            nn.Conv2d(32, 64, (3, 3)),  # 64,5,5
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True),
        )

        self.layer4 = nn.Sequential(
            nn.Conv2d(64, 128, (3, 3)),  # 128,3,3
            nn.BatchNorm2d(128),
            nn.ReLU(inplace=True),
        )

        self.fc = nn.Sequential(
            nn.Linear(128 * 3 * 3, 384),
            nn.ReLU(inplace=True),
            nn.Linear(384, 213)
        )

    def forward(self, x):
        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)
        # print(x.shape)
        x = x.view(x.size(0), -1)
        x = self.fc(x)
        return x



def modify(id,blood,bic,sht,nblood,ige,mi):
    sql_delete = "delete from ad2 where 住院号="+id
    cur.execute(sql_delete)
    db.commit()
    sql_delete = "delete from ad where 住院号="+id
    cur.execute(sql_delete)
    db.commit()
    b=[0]*121
    #net=torch.load("D://model_finals2.pkl")
    seg = pkuseg.pkuseg(model_name='default',user_dict = "D://皮炎参数//分词汇总.txt")
    dict_chengdu=np.load("D://data//dict_chengdu.npy")
    dict_yuansu=np.load("D://data//dict_yuansu.npy")
    dict_mi=np.load("D://data//dict_mi.npy")
    ways=np.load("D://data//ways.npy")
    stop=np.load("D://data//stop.npy")
    dict_chengdu=dict_chengdu.item()
    dict_yuansu=dict_yuansu.item()
    dict_mi=dict_mi.item()
    sht=str(sht)
    sht=sht.replace('阳性',' 1 ')
    sht=sht.replace('阴性',' 0 ')
    s=str(blood)+' '+str(bic)+' '+str(sht)+' '+str(nblood)+' '+str(ige)+' '+str(mi)
    for l in stop: 
        s=s.replace(l,' ')
    text=seg.cut(s)
    text.append('。')
    for ch in range(0,len(text)):
        if text[ch] in dict_mi.keys():
            if text[ch-1] in dict_chengdu.keys():
                b[dict_yuansu[text[ch]]]=float(dict_chengdu[text[ch-1]])
            elif text[ch+1] in dict_chengdu.keys():
                b[dict_yuansu[text[ch]]]=float(dict_chengdu[text[ch+1]])
            elif re.search(r'\d', text[ch+1] ):
                b[dict_yuansu[text[ch]]]=float(text[ch+1])
            else :
                b[dict_yuansu[text[ch]]]=float(3)
        elif text[ch] in dict_yuansu.keys():
            if re.search(r'\d', text[ch+1] ):
                b[dict_yuansu[text[ch]]]=float(text[ch+1])
            else :b[dict_yuansu[text[ch]]]=float(1)
    temp=np.array(b).reshape(11,11)
    inputs=np.array(temp)
    inputs=inputs[np.newaxis,np.newaxis,:,:]
    inputs=torch.tensor(inputs ,dtype=torch.float32)
    outputs = net(inputs)
    outputs=outputs.tolist()
    outputs=reduce(operator.add, outputs)
    out=""
    for i,_ in enumerate(outputs):
        if outputs[i]>0.8:
            out=out+ways[i]+","
    b[0]=id
    b2=str(b).replace('[','(')
    b2=b2.replace(']',')')
    b3="insert into ad2 values"+b2
    b4="insert into adgrp values"+b2
    print(b3)
    cur.execute(b3)
    db.commit()    
    cur.execute(b4)
    db.commit()   

    return out


if __name__ == "__main__":
    res = operation(id=sys.argv[1],blood=sys.argv[2],bic=sys.argv[3],sht = sys.argv[4],nblood=sys.argv[5],ige=sys.argv[6],mi=sys.argv[7])
    print(res)